import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

public class Demo1 {
    //文件便利目录,看某个输入的内容是在文件名或还是在文件内容当中.
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入要搜索的路径:");
        String s1 = scan.next();
        File file = new File(s1);

        if(!file.exists()) {
            System.out.println("文件不存在!");
            return;
        }

        if(!file.isDirectory()) {
            System.out.println("文件不是目录!");
            return;
        }

        System.out.println("请输入要查找的内容:");
        String s2 = scan.next();
        scanDir(file,s2);

    }

    private static void scanDir(File file, String s2) {
        File[] files = file.listFiles();

        if (files == null) {
            return;
        }

        for (File f : files) {
            if(f.isDirectory()) {
                scanDir(f,s2);
            }else {
                tryFind(f,s2);
            }
        }
    }

    private static void tryFind(File f, String s2) {
        if(f.getName().contains(s2)) {
            try {
                System.out.println("匹配文件:"+f.getCanonicalFile());
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try(InputStream inputStream = new FileInputStream(f)) {
            StringBuffer stringBuffer = new StringBuffer();
            Scanner scanner = new Scanner(inputStream);
            while(scanner.hasNextLine()) {
                stringBuffer.append(scanner.nextLine());
            }

            if(stringBuffer.indexOf(s2) >= 0) {
                System.out.println("匹配的内容文件:"+f.getAbsolutePath());
                return;
            }
        }catch(IOException E) {
            E.printStackTrace();
        }

    }
}
